# encoding=utf-8
"""
响应对象业务校验
"""
import json
from scrapy.exceptions import IgnoreRequest
from zc_core.middlewares.validate import BaseValidateMiddleware


class BizValidator(BaseValidateMiddleware):

    def validate_item(self, request, response, spider):
        # 商品下架
        json_data = json.loads(response.text)
        if json_data.get('code') == 400:
            sku_id = request.meta.get('skuId')
            raise IgnoreRequest('[item]%s：[%s]' % (json_data.get('message'), sku_id))
        return response

    def validate_order(self, request, response, spider):
        # 订单为空
        result = json.loads(response.text).get('data', {}).get('data', [])
        if len(result) == 0:
            spu_id = request.meta.get('spuId')
            raise IgnoreRequest('[order]订单为空：[%s]' % spu_id)
        return response

    def validate_group(self, request, response, spider):
        # 商品下架
        json_data = json.loads(response.text)
        if json_data.get('code') == 400:
            sku_id = request.meta.get('skuId')
            raise IgnoreRequest('[item]%s：[%s]' % (json_data.get('message'), sku_id))
        return response
